package com.lmaye.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.lmaye.common.ErrorInfo;
import com.lmaye.exceptions.CommonException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * Json工具类
 *
 * @author lmay.Zhou
 * @date 2019/4/23 17:12 星期二
 * @qq 379839355
 * @email lmay@lmaye.com
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JsonUtils {
    /**
     * 把Json字符串转成JAVA对象
     *
     * @param json Json字符串
     * @param cls  要转换的Java对象
     * @return Java对象
     */
    public static <T> T readValue(String json, Class<T> cls) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return objectMapper.readValue(json, cls);
        } catch (Exception e) {
            throw new CommonException(ErrorInfo.error("Json读取失败"), e);
        }
    }

    /**
     * 把Java对象转成字符串
     *
     * @param object 对象
     * @return Json字符串
     */
    public static String writeValueAsString(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new CommonException(ErrorInfo.error("Json转换失败"), e);
        }
    }
}